<template>
	<view class="publish">
		<view class="ph-tabs">
			<text :class="{active: inx==tabIndex}" v-for="(tab, inx) in tabs" :key="inx" @click="changeTab(inx)">{{tab}}</text>
		</view>
		<!-- 普通任务和特色活动 -->
		<view v-if="tabIndex!=0">
			<view class="title">
				<textarea name="" id="" rows="1" :value="taskActivity.title" @input="titleInput" placeholder-style="color: #999999;" maxlength="200" placeholder="自定义标题"></textarea>
			</view>
			<view class="content">
				<textarea :placeholder="tabIndex==1?'自定义任务':'自定义活动'" :value="taskActivity.content" @input="contInput" placeholder-style="color: #999999;" maxlength="500"></textarea>
			</view>
			<view class="upload-box">
				<upload-btn
					:icon-info="{width: '180rpx', icon: '/static/add.png'}"
					type="image"
					@chooseFile="chooseImages"
				></upload-btn>
				<view class="upload-tips">
					<text>上传图片</text>
				</view>
			</view>
			<view class="imgs all-img-file">
				<view class="img-box" v-for="(item, i) in taskActivity.sendImg" :key="i">
					<image class="img" :src="api.xiaodeObsUrl+item.path" mode="aspectFill"></image>
					<image class="close" @click="del2Images(i, taskActivity.sendImg)" src="/static/chat/close.png" mode="aspectFill"></image>
				</view>
			</view>
			<view class="set-box" v-if="tabIndex==2">
				<view class="set-item">
					<picker class="picker-box" @change="typeChange" :value="typeIndex" :range="allType">
						<view class="uni-input">{{allType[typeIndex] || '设置活动类型'}}</view>
					</picker>
					<uni-icons type="right" size="28rpx" color="#999"></uni-icons>
				</view>
				<view class="set-item" @click="selectDate=true">
					<text class="text">{{endDate?endDate:'设置截止时间'}}</text>
					<uni-icons type="right" size="28rpx" color="#999"></uni-icons>
				</view>
			</view>
			<view class="bottom-btn">
				<view class="publish-now">
					<text @click="publishTask()" :style="{opacity: handleBtn(taskActivity)?1:.3}">{{activityId && tabIndex==2?'确认修改':'立即发布'}}</text>
				</view>
			</view>
		</view>
		<view v-else>
			<view class="content ">
				<text-editor :id-name="`editor${tabIndex}`" :ref="`editor${tabIndex}`" :userId="userId" :info="editorInfoOri" @chooseFile="chooseFile"></text-editor>
			</view>
			<view class="all-img-file">
				<view class="imgs" v-if="showFiles.sendimgs">
					<view class="img-box" v-for="(item, i) in showFiles.sendimgs" :key="i">
						<image class="img" :src="api.xiaodeObsUrl+item.path" mode="aspectFill"></image>
						<image class="close" @click="delImages(i)" src="/static/chat/close.png" mode="aspectFill"></image>
					</view>
				</view>
				<view class="video" v-if="showFiles.files">
					<view class="video-box" :data-url="showFiles.files[0].path" v-if="showFiles.sendfiles.length>0">
						<zy-video 
							:ref="'videoRef'"
							:refi="'videoRef'"
							:width="utils.getpx(686)"
							:height="utils.getpx(386)"
							@playVideo="playVideo"
							:src="showFiles.files[0].path"></zy-video>
						<image class="close" @click="delFiles(0)" src="/static/chat/close.png" mode="aspectFill"></image>
					</view>
				</view>
			</view>
			<view class="bottom-btn">
				<view class="publish-now">
					<text @click="confirmPublish()" :style="{opacity: utils.editorCont(editorInfoOri.content)?1:.3}">发布</text>
				</view>
			</view>
		</view>
		<uni-transition mode-class="fade"
			:styles="utils.transitionStyles.bg" :show="jurPopup || selectDate || selectType" @click="closePopup()">
		</uni-transition>
		<uni-transition mode-class="fade"
			:styles="utils.transitionStyles.fade"
			:show="jurPopup">
			<view class="jur-popup popup-top">
				<view class="jp-item" v-for="i in 3" :key="i">
					<uni-icons size="50rpx" type="reload"></uni-icons>
					<view class="">
						<text>公开</text>
						<view>所有人可见</view>
					</view>
				</view>
			</view>
		</uni-transition>
		<!-- 活动时间选择 -->
		<uni-transition :mode-class="['slide-bottom']"
			:styles="selectClass"
			:show="selectDate">
			<view class="show-date">
				<date-picker @onCancel="onCancel" @onConfirm="onConfirm" :startDate="accountDate"  :defaultValue="accountDate">
				</date-picker>
			</view>
		</uni-transition>
	</view>
</template>
<script>
import SparkMD5 from 'spark-md5'
import md5Str from '@/static/md5.min.js'
import textEditor from '../student/components/text-editor.vue'
import uploadBtn from '../student/components/select-upload-file.vue'
import datePicker from '@/components/date-picker/date-picker.vue'
export default {
	components: {
		textEditor,
		uploadBtn,
		datePicker
	},
	data() {
		return {
			tabs: ['新鲜事', '基础任务', '特色活动'],
			tabIndex: 0,
			filesOri: { // 新鲜事上传的图片和文件
				sendimgs: [],
				sendfiles: []
			},
			editorInfoOri: { // 新鲜事内容
				content: '',
				showUpload: false, // 是否显示上传框
				placeText: '成长历程的一切感受，都值得记录~',
				bottom: '142rpx', // 上传框到底部的距离
				formats: 'video' // 上传文件类型
			},
			showFiles: {}, // 当前需要显示的图片和文件
			jurPopup: false,
			userId: '', // 用户ID
			taskInfo: { // 基础任务信息
				sendImg: [], 
				content: '',
				title: ''
			},
			activityInfo: { // 活动信息
				sendImg: [], 
				content: '',
				title: ''
			},
			taskActivity: {}, // 当前选中的任务或者活动的信息
			selectDate: false, // 选择活动截止时间
			selectClass: { // 时间选择弹窗样式
				position: 'absolute',
				width: '100%',
				bottom: '0',
				left: 0,
				height: '670rpx',
				'z-index': 9
			},
			endDate: '', // 截止时间
			accountDate: '2023-3-15', // 当前时间
			selectType: false, // 选择活动类型弹窗
			typeIndex: -1, // 类型下标
			allType: ['德育', '智育', '体育', '美育', '劳育'],
			activityId: '' // 活动id，修改活动的时候才会有
		}
	},
	onShow(){
		uni.removeStorageSync('xdReviewerList')
	},
	onLoad(options){
		this.accountDate = this.utils.initDateDay()
		this.userId = uni.getStorageSync('tokenObj').userId;
		
		// id存在代表是编辑特色活动
		if (options.id) {
			this.activityId = options.id
			this.getActivityParInfo(options.id)
			
		}
	},
	methods: {
		// 切换类型
		changeTab(i){
			this.tabIndex = i;
			if(i>=1) {
				this.taskActivity = i==1?this.taskInfo:this.activityInfo
				return
			}
			this.showFiles = this.filesOri
			if(i==0){
				this.$nextTick(()=>{
					this.$refs[`editor${i}`].closePopup()
				})
			}
		},
		// 输入标题
		titleInput(e){
			this.taskActivity.title = e.detail.value
		},
		// 输入内容
		contInput(e){
			this.taskActivity.content = e.detail.value

		},
		// 确认发布新鲜事
		confirmPublish(){
			let info = this.filesOri
			let images = info.sendimgs || [],
				fs = info.sendfiles || [];
			let list = images.concat(fs)

			this.creatCampusOriginal(list)
		},
		// 创建新鲜事
		creatCampusOriginal(list){
			if(!this.editorInfoOri.content){
				this.utils.showToast('内容不能为空')
				return
			}
			this.api.post('share/creatCampusOriginal', {
				content: this.editorInfoOri.content,
				files: JSON.stringify(list),
				state: 1
			}).then(res=>{
				if(res.data.state !='ok') return;
				this.editorInfoOri.content = ''
				this.$refs.editor0.closeHtml()
				this.filesOri = {}
				uni.navigateTo({
					url: '/pages/recommend/publish-success?type=1'
				})
			})
		},
		// 发布任务或者活动
		publishTask(){
			if(!this.taskActivity.title){
				this.utils.showToast('任务标题不能为空')
				return
			}
			if(!this.taskActivity.content){
				this.utils.showToast('任务内容不能为空')
				return
			}
			if(this.tabIndex==2){
				
				let msgTips = ''
				if(!this.endDate){
					msgTips = '请选择截止时间'
				} else if(this.typeIndex==-1) {
					msgTips = '请选择评活动类型'
				}
				if(msgTips){
					this.utils.showToast(msgTips)
					return
				}
				this.publishActivity()
				return
			}
			// 发布任务
			this.api.get('ordinary/publishTask', {
				content: this.taskInfo.content,
				title: this.taskInfo.title,
				pictures: JSON.stringify(this.taskInfo.sendImg),
				score: 3
			}).then(res=>{
				if(res.data.state !='ok') return;
				uni.navigateTo({
					url: '/pages/recommend/publish-success?type=1'
				})
			})
		},
		// 处理按钮展示
		handleBtn(task){
			if(task.title && task.content) {
				if(this.tabIndex == 1){
					return true
				} else if(this.endDate&&this.typeIndex!=-1) {
					return true
				} else {
					return false
				}
			}else{
				return false
			}
		},
		// 发布活动
		publishActivity(){
			let path = 'activity/publishActivity'
			const params = {
				content: this.activityInfo.content,
				title: this.activityInfo.title,
				files: JSON.stringify(this.activityInfo.sendImg),
				score: 10,
				endDate: this.endDate.split('.').join('-'),
				typeName: this.allType[this.typeIndex]
			}
			if (this.activityId) {
				params.activityId = this.activityId
				path = 'activity/updateActivity'
			}
			this.api.post(path, params).then(res=>{
				if(res.data.state !='ok') return;
				// 跳转到发布成功页面
				uni.navigateTo({
					url: `/pages/recommend/publish-success?type=1&id=${this.activityId}`
				})
			})
		},
		// 选择文件
		chooseFile(type, list, sendList){
			let info = this.filesOri
			let files = info.files || [],
				sendimgs = info.sendimgs || [],
				sendfiles = info.sendfiles || []
			if(type==1){
				let fun = ()=>{
					files = []
					sendfiles = []
					sendimgs = sendimgs.concat(sendList)

					info.sendimgs = sendimgs
					info.files = files
					info.sendfiles = sendfiles
					this.showFiles = info
					if(sendimgs.length>9){
						this.utils.showToast('最多可以上传9张图片')
						sendimgs.splice(9)
					}
				}
				if(sendfiles.length>0){
					this.utils.showModal('', '图片和视频只能选择一种上传，确定要覆盖视频吗？', fun)
					return
				}
				fun()
			}else{
				let fun = ()=>{
					files = list
					sendimgs = []
					sendfiles = sendList

					info.sendimgs = sendimgs
					info.files = files
					info.sendfiles = sendfiles
					this.showFiles = info
				}
				if(sendimgs.length>0){
					this.utils.showModal('', '图片和视频只能选择一种上传，确定要覆盖图片吗？', fun)
					return
				}
				fun()
				
			}
			
		},
		chooseImages(type, list, sendList){
			this.taskActivity.sendImg = sendList
		},
		playVideo(){
			this.$refs.videoRef.pauseVideo();
		},

		delImages(i){
			this.filesOri.sendimgs.splice(i, 1)
		},
		delFiles(i){
			this.filesOri.sendfiles.splice(i, 1)
			
		},
		del2Images(i, item){
			// item.splice(i, 1)
			this.taskActivity.sendImg.splice(i, 1)
		},
		// 取消选择关闭弹窗
		onCancel(e){
			this.closePopup()
		},
		// 确认选择时间
		onConfirm(e){
			let date = e.dateValue
			this.endDate = date?date.split('-').join('.'):'';
			this.closePopup();
		},
		// 选择活动类型
		typeChange(e){
			this.typeIndex = e.detail.value
		},
		closePopup(){
			this.selectDate = this.jurPopup = this.selectType = false 
		},
		// 获取活动详情
		getActivityParInfo(id){
			this.api.get('activity/getActivityInfo', {
				activityId: id
			}).then(res=>{
				if(res.data.state != 'ok') return
				const data = res.data.activity
				const { end_date, files, title, content, type_name} = data
				this.activityInfo = {
					sendImg: JSON.parse(files), 
					content,
					title
				}
				this.typeIndex = this.allType.indexOf(type_name)
				this.endDate = end_date.split(' ')[0]
				this.changeTab(2)
			})
		},
	}
}

</script>
<style lang="less" scoped>
	.publish{
		min-height: 100vh;
		/* #ifdef H5 */
		min-height: calc(100vh - 44px);
		/* #endif */
		.ph-tabs{
			padding: 32rpx 16rpx;
			margin: 0 16rpx;
			display: flex;
			align-items: center;
			border-bottom: 4rpx solid #f2f2f2;
			text{
				margin-right: 40rpx;
				display: inline-block;
				width: 180rpx;
				height: 64rpx;
				line-height: 60rpx;
				text-align: center;
				border-radius: 10rpx;
				font-size: 26rpx;
				border: 1rpx solid #999999;
				box-sizing: border-box;
				color: #666666;
				&.active{
					background-color: transparent;
					border: 2rpx solid #333;
					color: #333;
					font-weight: 600;
				}
			}
		}
		.title{
			margin: 20rpx 32rpx 0;
			padding: 40rpx 0;
			border-bottom: 4rpx dotted #E2E4EA;
			textarea{
				width: 100%;
				height: 64rpx;
				font-size: 32rpx;
				font-weight: bold;
			}
		}
		.content{
			margin: 32rpx 32rpx;
			textarea{
				width: 100%;
				height: 100rpx;
				font-size: 28rpx;
				font-weight: bold;
			}
		}
		.upload-box{
			margin-left: 50rpx;
		}
		.upload-tips{
			margin-top: 10rpx;
			width: 180rpx;
			text-align: center;
			line-height: 40rpx;
			color: #999999;
		}
		.jurisdiction{
			padding-left: 32rpx;
			margin-bottom: 16rpx;
			.text-btn{
				display: inline-block;
				width: 108rpx;
				height: 40rpx;
				line-height: 40rpx;
				text-align: center;
				background-color: #f2f2f2;
				color: #aaa;
				font-size: 24rpx;
				border-radius: 20rpx;
			}
		}
		
		.jur-popup{
			width: 690rpx;
			height: 400rpx;
			background-color: #fff;
			border-radius: 10rpx;
			padding: 32rpx 40rpx;
			box-sizing: border-box;
			.jp-item{
				display: flex;
				align-items: center;
				font-size: 32rpx;
				margin-bottom: 32rpx;
				&.active{
					color: #55acee;
				}
				.uni-icons{
					margin-right: 16rpx;
				}
			}
		}
		.all-img-file{
			.video-box{
				margin: 0 32rpx;
				position: relative;
			}
			.close{
				position: absolute;
				top: 0;
				right: 0;
				width: 40rpx;
				height: 40rpx;
			}
		}
		.img-box{
			display: inline-block;
			width: 215rpx;
			height: 215rpx;
			position: relative;
			margin-right: 20rpx;
			margin-bottom: 20rpx;
			&:nth-child(3n){
				margin-right: 0;
			}
		}
		.imgs{
			font-size: 0;
			padding: 32rpx;
			.img{
				width: 215rpx;
				height: 215rpx;
				margin-right: 20rpx;
				border-radius: 8rpx;
				margin-bottom: 20rpx;
				&:nth-child(3n){
					margin-right: 0;
				}
			}
			
		}
		
		.bottom-btn{
			height: 142rpx;
			.publish-now{
				position: fixed;
				bottom: 0;
				/* #ifdef H5 */
				left: var(--window-left);
				right: var(--window-right);
				/* #endif */
				/* #ifndef H5 */
				left: 0;
				right: 0;
				/* #endif */
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 24rpx 32rpx;
				background-color: #fff;
				box-shadow: 0 2rpx 6rpx 0 rgba(208, 208, 208, .5);
				text{
					display: inline-block;
					width: 100%;
					height: 94rpx;
					line-height: 94rpx;
					text-align: center;
					background-color: #2D74F3;
					font-size: 32rpx;
					color: #fff;
					border-radius: 20rpx;
				}
			}
		}
		.set-box{
			margin-left: 32rpx;
		}
		.set-item{
			width: 256rpx;
			height: 64rpx;
			text-align: center;
			border: 1rpx solid #999999;
			border-radius: 32rpx;
			color: #999999;
			margin-bottom: 32rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 20rpx;
			box-sizing: border-box;
			.text{
				margin-right: 16rpx;
			}
		}
		.picker-box{
			width: 100%;
			text-align: left;
		}
		.upload-img{
			margin-top: 70rpx;
			width: 180rpx;
			text-align: center;
			margin-left: 32rpx;
			text{
				margin-top: 20rpx;
				display: block;
				font-size: 28rpx;
				color: #999999;
			}
		}
		.add-img{
			width: 180rpx;
			height: 180rpx;
		}
	}
	.type-head{
		height: 88upx;
		background-color: #FFFFFF;
		border-bottom: 1px solid #e5e5e5;
		padding: 0 40upx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 17px;
		.cancal{
			color: #888;
		}
		.confirm {
			color: #6ba1ff;
		}
	}
	.picker-view {
		width: 100%;
		height: 670rpx;
		background: #fff;
		.item {
			line-height: 100rpx;
			text-align: center;
		}
	}
</style>